<template>
    <div>
        <Input search enter-button placeholder="在所有新闻中搜索" @on-search="search" v-model="keywords"/>
        <Button type="success" icon="md-add" @click="modal=true">添加</Button>
        <Button type="error" icon="md-close" @click="removes">批量删除</Button>
        <Table border ref="selection" :columns="columns" :data="$store.getters.getNews" @on-select="selectNews" @on-select-cancel="selectNews" @on-select-all="selectNews" @on-select-all-cancel="selectNews"></Table>
        <div class="center">
            <div class="center-right">
                <Tooltip placement="right-end"></Tooltip>
            </div>
        </div>
        <Page :total="$store.getters.getTotal" size="small" show-elevator show-sizer @on-change="pageChanged" @on-page-size-change="limitChanged"/>
        <Modal
            v-model="modal"
            title="数据处理"
            footer-hide
            @on-cancel="clearForm">
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
                <FormItem label="Title" prop="title">
                    <Input v-model="formValidate.title" placeholder="Enter your title"></Input>
                </FormItem>
                <FormItem label="Content" prop="content">
                    <Input v-model="formValidate.content" placeholder="Enter your content"></Input>
                </FormItem>
                <FormItem label="Author" prop="author">
                    <Input v-model="formValidate.author" placeholder="Enter the autor"></Input>
                </FormItem>
                <FormItem label="Keyword" prop="keyword">
                    <Input v-model="formValidate.keyword" placeholder="Enter the keyword"></Input>
                </FormItem>
                
                <FormItem>
                    <Button type="primary" @click="handleSubmit('formValidate')">提交</Button>
                    <Button @click="handleReset('formValidate')" style="margin-left: 8px">重置</Button>
                </FormItem>
            </Form>
        </Modal>
        <Modal v-model="commentmodel" fullscreen title="评论管理" footer-hide @on-cancel="clearType">
            <Select  v-model="defaultValue" style="width:200px" @on-change="selectValue">
                <Option value="1">已通过</Option>
                <Option value="2">不通过</Option>
            </Select>
            <Button type="success" icon="md-checkmark" @click="checkSuccess">批量通过</Button>
            <Button type="error" icon="md-close" @click="checkUnsuccess">批量不通过</Button>
            <Button type="error" icon="md-close" @click="commentDelete">批量删除</Button>
            <Button type="primary" icon="md-add" @click="addcomment">新增评论</Button>
            <Table border :columns="commentcolumns" :data="commentData" 
            @on-select="commentSelectChange" @on-select-cancel="commentSelectChange" @on-select-all="commentSelectChange" @on-select-all-cancel="commentSelectChange"></Table>
            <Page :total="comtotal" size="small" :current="compage" show-elevator show-sizer @on-change="onChangePage" @on-page-size-change="onChangeLimit" />
        </Modal>
        <Modal
            v-model="commentFrom"
            title="数据处理"
            footer-hide>
            <Form ref="commentformValidate" :model="commentformValidate" :rules="commentruleValidate" :label-width="80">
                <FormItem label="Title" prop="news">
                    <Input v-model="commentformValidate.news" placeholder="Enter your title"></Input>
                </FormItem>
                <FormItem label="Content" prop="content">
                    <Input v-model="commentformValidate.content" placeholder="Enter your content"></Input>
                </FormItem>
                <FormItem label="Author" prop="author">
                    <Input v-model="commentformValidate.author" placeholder="Enter the autor"></Input>
                </FormItem>
                <FormItem>
                    <Button type="primary" @click="commenthandleSubmit('commentformValidate')">提交</Button>
                    <Button @click="commenthandleReset('commentformValidate')" style="margin-left: 8px">重置</Button>
                </FormItem>
            </Form>
        </Modal>
    </div>
</template>
<script>
import { mapActions, mapGetters } from "vuex";
export default {
  data() {
    return {
      host: "http://10.31.156.62:3000",
      columns: [
        {
          type: "selection",
          width: 60,
          align: "center"
        },
        {
          title: "标题",
          key: "title",
          tooltip:true
        },
        {
          title: "内容",
          key: "content",
          tooltip:true
        },
        {
          title: "作者",
          key: "author",
          tooltip:true
        },
        {
          title: "关键字",
          key: "keyword",
          tooltip:true
        },
        {
          title: "上传时间",
          key: "pushtime",
          tooltip:true
        },
        {
          title: "评论数",
          key: "commentnum",
          width:80,
          tooltip:true
        },
        {
          title: "Action",
          key: "action",
          width: 200,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "warning",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.edit(params.row._id);
                    }
                  }
                },
                "修改"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.remove(params.row._id);
                    }
                  }
                },
                "删除"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  on: {
                    click: () => {
                      this.commentState(params.row._id);
                    }
                  }
                },
                "查看评论"
              )
            ]);
          }
        }
      ],
      commentcolumns: [
        {
          type: "selection",
          width: 60,
          align: "center"
          
        },
        {
          title: "news",
          key: "news"
        },
        {
          title: "Content",
          key: "content"
        },
        {
          title: "Author",
          key: "author"
        },
        {
          title: "Time",
          key: "time"
        },
        {
          title: "state",
          key: "state",
          align: "center"
        }
      ],
      total: "",
      newsData: [],
      keywords: "",
      modal: false,
      newsSelected: [],
      commentData:[],
      commentmodel: false,
      commentFrom: false,
      comtotal: 0,
      compage: 1,
      comlimit: 10,
      selectType:'',
      newsId: "",
      defaultValue:'',
      comUpdatearr:[],
      formValidate: {
        title: "",
        content: "",
        author: "",
        keyword: ""
      },
      commentformValidate: {
        news: "",
        content: "",
        author: "",
        time: ""
      },
      ruleValidate: {
        title: [
          {
            required: true,
            message: "The title cannot be empty",
            trigger: "blur"
          }
        ],
        content: [
          {
            required: true,
            message: "content cannot be empty",
            trigger: "blur"
          }
        ],
        author: [
          {
            required: true,
            message: "author cannot be empty",
            trigger: "change"
          }
        ],
        keyword: [
          { required: true, message: "Please select gender", trigger: "change" }
        ]
      },
      commentruleValidate: {
        news: [
          {
            required: true,
            message: "The title cannot be empty",
            trigger: "blur"
          }
        ],
        content: [
          {
            required: true,
            message: "content cannot be empty",
            trigger: "blur"
          }
        ],
        author: [
          {
            required: true,
            message: "author cannot be empty",
            trigger: "blur"
          }
        ]
      }
    };
  },
  methods: {
    ...mapActions(["changePage", "changeLimit", "changeNews"]),
    getList() {
      this.axios({
        url: `${this.host}/news/list`,
        method: "post",
        data: {
          belong: this.$store.getters.getNodeSelected._id,
          page: this.$store.getters.getPage,
          rows: this.$store.getters.getLimit
        }
      }).then(res => {
        this.changeNews(res.data.rows);
      });
    },
    clearForm() {
      this.formValidate = {};
    },
    edit(id) {
      this.axios({
        url: `${this.host}/news/data/${id}`,
        method: "get"
      }).then(res => {
        this.formValidate = res.data;
        this.modal = true;
      });
    },
    remove(id) {
      this.$Modal.confirm({
        title: "确认删除",
        content: "<p>你确定要删除吗</p>",
        onOk: () => {
          this.axios({
            url: `${this.host}/news/data/${id}`,
            method: "delete"
          }).then(res => {
            this.getList();
          });
        }
      });
    },
    selectNews(selections) {
      this.newsSelected = selections;
    },
    removes() {
      var ids = [];
      if (this.newsSelected.length > 0) {
        this.newsSelected.forEach((value, index) => {
          ids.push(value._id);
        });
        this.$Modal.confirm({
          title: "确认删除",
          content: "<p>你确定要删除这些新闻吗</p>",
          onOk: () => {
            this.axios({
              url: `${this.host}/news/data/removes`,
              method: "post",
              data: {
                ids: ids.toString()
              }
            }).then(res => {
              this.getList();
              this.newsSelected = [];
              this.$Message.success("删除成功");
            });
          }
        });
      } else {
        this.$Message.warning("至少选中一个");
      }
    },
    search() {
      this.axios({
        url: `${this.host}/news/list`,
        method: "post",
        data: {
          title: this.keywords
        }
      }).then(res => {
        this.changeNews(res.data.rows);
      });
    },
    handleSubmit(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          if (this.formValidate._id) {
            //edit
            this.axios({
              url: `${this.host}/news/data/${this.formValidate._id}`,
              method: "put",
              data: this.formValidate
            }).then(res => {
              this.getList();
              this.formValidate = {};
            });
          } else {
            //add
            delete this.formValidate._id;
            var nodeSelected = this.$store.getters.getNodeSelected;
            this.axios({
              url: `${this.host}/news/data`,
              method: "post",
              data: Object.assign(this.formValidate, {
                belong: nodeSelected._id + nodeSelected.path,
                commentnum: 0,
                pushtime: new Date()
              })
            }).then(res => {
              this.getList();
              console.log(this.formValidate)
              this.formValidate = {};
            });
          }

          this.$Message.success("Success!");
          this.modal = false;
        } else {
          this.$Message.error("Fail!");
          this.modal = false;
        }
      });
    },
    handleReset(name) {
      this.$refs[name].resetFields();
    },
    commentState(id) {
      this.newsId = id;
      this.axios({
        url: `${this.host}/comment/list`,
        method: "post",
        data: {
          id: this.newsId,
          rows: this.comlimit,
          page:this.compage
        }
      }).then(res => {
        this.commentmodel = true;
        this.commentData = res.data.rows;
        this.comtotal=res.data.total
      });
    },
    selectValue(value) {
      this.selectType=value;
      this.axios({
         url:`${this.host}/comment/list`,
         method:'post',
         data:{
           type:this.selectType,
           id:this.newsId,
           page:1,
           rows:this.comlimit
         }
      }).then(res=>{
          this.commentData=res.data.rows;
          this.comtotal=res.data.total;
      })
    },
    changePageList(){
       this.axios({
         url:`${this.host}/comment/list`,
         method:'post',
         data:{
           type:this.selectType,
           id:this.newsId,
           page:this.compage,
           rows:this.comlimit
         }
      }).then(res=>{
          this.commentData=res.data.rows;
          this.comtotal=res.data.total;
      })
    },
    addcomment() {
      this.commentFrom = true;
    },
    commenthandleSubmit(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          this.commentFrom = false;
          this.commentformValidate["time"] = new Date().toLocaleDateString();
          this.commentformValidate["newsid"] = this.newsId;
          this.commentformValidate["state"] = "不通过";
          this.axios({
            url: `${this.host}/comment/data`,
            method: "post",
            data: this.commentformValidate
          }).then(res => {
            this.$Message.success("Add Success!");
            this.changePageList();
            this.commentformValidate = {};
            //this.defaultValue='';
          });
        } else {
          this.$Message.error("Fail!");
        }
      });
    },
    commenthandleReset(name) {
      this.$refs[name].resetFields();
    },
    onChangePage(page) {
      this.compage = page;
      if(this.selectType){
          this.changePageList();
      }else{
          this.commentState(this.newsId);
      }
    },
    onChangeLimit(limit) {
      this.comlimit = limit;
      if(this.selectType){
           this.changePageList();
      }else{
          this.commentState(this.newsId);
      }
      
    },
    clearType(){
        this.axios({
            url:`${this.host}/comment/list`,
            method:'post',
            data:{
                id:this.newsId,
                type:1
            }
        }).then(res=>{
            this.axios({
                url:`${this.host}/news/data/${this.newsId}`,
                method:'put',
                data:{
                    commentnum:res.data.total
                }
            }).then(res=>{
                this.getList()
            })
        })
      this.selectType='';
      this.compage=1;
      this.comlimit=10;
      this.defaultValue='';
    },
    pageChanged(page) {
      this.changePage(page);
      this.getList();
    },
    limitChanged(limit) {
      this.changeLimit(limit);
      this.getList();
    },
    commentSelectChange(val){
      this.comUpdatearr=val;
    },
    checkSuccess(){
      var ids=[];
      if(this.comUpdatearr.length>0){
          this.$Modal.confirm({
          title: "确认通过",
          content: "<p>你确定要通过这些新闻吗</p>",
          onOk: () => {
            for(let i =0 ;i<this.comUpdatearr.length;i++){
               ids.push(this.comUpdatearr[i]._id);
            }
            this.axios({
               url:`${this.host}/comment/data/updates`,
               method:'post',
               data:{
                 ids:ids.toString()
               }
            }).then(res => {
              this.$Message.success("审核通过");
              this.changePageList();             
            });
          }
        });
      }else{
          this.$Message.error('至少选择一条信息');
      }
    },
    checkUnsuccess(){
      var ids=[];
      if(this.comUpdatearr.length>0){
          this.$Modal.confirm({
          title: "确认删除",
          content: "<p>你确定要不通过这些新闻吗</p>",
          onOk: () => {
            for(let i =0 ;i<this.comUpdatearr.length;i++){
               ids.push(this.comUpdatearr[i]._id);
            }
            this.axios({
               url:`${this.host}/comment/data/unupdates`,
               method:'post',
               data:{
                 ids:ids.toString()
               }
            }).then(res => {
              this.$Message.success("审核不通过");
              this.changePageList();          
            });
          }
        });
      }else{
          this.$Message.error('至少选择一条信息');
      }
    },
    commentDelete(){
      var ids=[];
      if(this.comUpdatearr.length>0){
          this.$Modal.confirm({
          title: "确认删除",
          content: "<p>你确定要删除这些新闻吗</p>",
          onOk: () => {
            for(let i =0 ;i<this.comUpdatearr.length;i++){
               ids.push(this.comUpdatearr[i]._id);
            }
            this.axios({
               url:`${this.host}/comment/data/removes`,
               method:'post',
               data:{
                 ids:ids.toString()
               }
            }).then(res => {
              this.$Message.success("删除成功");
              this.changePageList();            
            });
          }
        });
      }else{
          this.$Message.error('至少选择一条信息');
      }
    }
  },
  computed: {
    getTotal() {
      return this.$store.getters.getTotal;
    },
    getLimit() {
      return this.$store.getters.getLimit;
    }
  },
  mounted() {}
};
</script>

